<?php include("menu.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link rel="stylesheet" type="text/css" href="datepicker/css/smoothness/jquery-ui-1.7.2.custom.css">
<script type="text/javascript" src="datepicker/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="datepicker/js/jquery-ui-1.7.2.custom.min.js"></script>


<script type="text/javascript" src="jquery-autocomplete/jquery.autocomplete.js"></script>
<script type="text/javascript" src="jquery-autocomplete/lib/jquery.bgiframe.min.js"></script>
<script type="text/javascript" src="jquery-autocomplete/lib/jquery.ajaxQueue.js"></script>
<script type="text/javascript" src="jquery-autocomplete/lib/thickbox-compressed.js"></script>
<link rel="stylesheet" href="jquery-autocomplete/jquery.autocomplete.css"/>

<script type="text/javascript">
	function CheckList(){
        if(document.formaddlist.list.value == "" )
        {
            alert('กรุณาระบุรายการด้วยค่ะ');
            document.formaddlist.list.focus();
            return false;
        }
        if(document.formaddlist.qty.value == "" )
        {
            alert('กรุณาระบุจำนวนด้วยค่ะ');
            document.formaddlist.qty.focus();
            return false;
        }
        if(document.formaddlist.price.value == "" )
        {
            alert('กรุณาระบุราคาต่อหน่วยด้วยค่ะ');
            document.formaddlist.price.focus();
            return false;
        }
        if(document.formaddlist.total.value == "" )
        {
            alert('กรุณาระบุจำนวนเงินด้วยค่ะ');
            document.formaddlist.total.focus();
            return false;
        }
        document.formaddlist.submit();
	}

	function setFocus(){
		document.formaddlist.list.focus();
	}

	function totalcash(){
		var elm1 = document.getElementById("qty").value;
		var elm2 = document.getElementById("price").value;
		var result;
		var total;

		if(document.formaddlist.price.value!="" && document.formaddlist.qty.value!=""){
		result = elm2*elm1;
		
		document.getElementById("total").value = result;
		}
	}
	
	function pricecash(){
		var elm1 = document.getElementById("qty").value;
		var elm2 = document.getElementById("total").value;
		var result;
		var total;

		if(document.formaddlist.total.value!="" && document.formaddlist.qty.value!=""){
		result = Math.round((elm2/elm1)*100)/100;
		
		document.getElementById("price").value = result;
		}
	}

	function CheckDate(){
        if(document.formadd.date.value == "" )
        {
            alert('กรุณาระบุวันที่ด้วยค่ะ');
            document.formadd.date.focus();
            return false;
        }
        
        if(document.formadd.bill.value == "" )
        {
            alert('กรุณาระบุเลขที่บิลด้วยค่ะ');
            document.formadd.bill.focus();
            return false;
        }
        document.formadd.submit();
	}
</script>
<?php
$Query = "SELECT product_name FROM product ";
$objQuery = mysql_query($Query) or die("Error Query [" . $Query . "]");
	while($row = mysql_fetch_assoc($objQuery)){
		$line1[]=array($row["product_name"]);
	}
?> 
<script type="text/javascript">
$(document).ready(function(){

	var str_month = <?php echo json_encode($line1).';'; ?>

	$("#list").autocomplete( str_month , {
		mustMatch: false,
		autoFill: false,
		matchContains:true,
		});


    var dateBefore=null;
    $("#date").datepicker({
        dateFormat: 'dd-mm-yy',
        dayNamesMin: ['อา', 'จ', 'อ', 'พ', 'พฤ', 'ศ', 'ส'],
        monthNamesShort: ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฎาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'],
        changeMonth: true,
        changeYear: true ,
        beforeShow:function(){
            if($(this).val()!=""){
                var arrayDate=$(this).val().split("-");
                arrayDate[2]=parseInt(arrayDate[2])-543;
                $(this).val(arrayDate[0]+"-"+arrayDate[1]+"-"+arrayDate[2]);
            }
            setTimeout(function(){
                $.each($(".ui-datepicker-year option"),function(j,k){
                    var textYear=parseInt($(".ui-datepicker-year option").eq(j).val())+543;
                    $(".ui-datepicker-year option").eq(j).text(textYear);
                });
            },50);

        },
        onChangeMonthYear: function(){
            setTimeout(function(){
                $.each($(".ui-datepicker-year option"),function(j,k){
                    var textYear=parseInt($(".ui-datepicker-year option").eq(j).val())+543;
                    $(".ui-datepicker-year option").eq(j).text(textYear);
                });
            },50);
        },
        onClose:function(){
            if($(this).val()!="" && $(this).val()==dateBefore){
                var arrayDate=dateBefore.split("-");
                arrayDate[2]=parseInt(arrayDate[2])+543;
                $(this).val(arrayDate[0]+"-"+arrayDate[1]+"-"+arrayDate[2]);
            }
        },
        onSelect: function(dateText, inst){
            dateBefore=$(this).val();
            var arrayDate=dateText.split("-");
            arrayDate[2]=parseInt(arrayDate[2])+543;
            $(this).val(arrayDate[0]+"-"+arrayDate[1]+"-"+arrayDate[2]);
        }

    });

});
</script>
</head>
<body onload="setFocus()">
<?php
if($_GET['Action']=='Cancle'){
	mysql_query("DELETE FROM buy_detail_session");
	header('Location: buy_history.php');
}

if($_GET['Action']=='delete'){
	mysql_query("DELETE FROM buy_detail_session WHERE buy_detail_ses_id = '".$_GET['id']."' ");
	header('Location: buy_history.php');
}

if($_GET['action']=='addlist'){
	
	if($_POST['list']!="" && $_POST['qty']!="" && $_POST['price']!="" && $_POST['total']!=""){
	$iQuery = mysql_query("SELECT product_id FROM product WHERE product_name = '".$_POST["list"]."'");
	$iRow = mysql_fetch_array($iQuery);
	
	if($iRow){
		mysql_query("INSERT INTO buy_detail_session (product_id,qty_ses,price_ses,total_ses) VALUES ('".$iRow['product_id']."','".$_POST["qty"]."','".$_POST["price"]."','".$_POST["total"]."')");
		header('Location: buy_history.php');
	} else {
		$save = "ไม่มีชื่อสินค้านี้ กรุณาเพิ่มชื่อสินค้านี้ก่อนค่ะ";
	}
	
	} else {
		$save = "กรุณากรอกข้อมูลให้ครบค่ะ";
	}
}

//บันทึกข้อมูลลง
if($_GET["action"]=='add') {
		
		if($_POST['date'] != "" && $_POST['bill'] != ""){
			$dmy = $_POST["date"];
			$d = substr($dmy, 0, 2);
			$m = substr($dmy, 3, 2);
			$y = substr($dmy, 6, 4);
			$date = ($y - 543) . '-' . $m . '-' . $d;
			
			//เพิ่มข้อมูลลงใน buy_his
			mysql_query("INSERT INTO buy_history (buy_his_date,buy_his_bill) VALUES ('".$date."','".$_POST['bill']."')");
			
			//ค้นหารหัส his_id เพื่อใช้ไปเก็บใน buy_detail
			$numBh = mysql_query("SELECT max(buy_his_id) as buy_his_id FROM buy_history");
			$BhRow = mysql_fetch_array($numBh);
			
			//บันทึกข้อมูลรายการสินค้าจากเซสชั่น
			$hisQuery = mysql_query("SELECT * FROM buy_detail_session");
			
			while ($hisRow = mysql_fetch_array($hisQuery)) {
				mysql_query("INSERT INTO buy_detail (buy_his_id,product_id,qty,price,total) VALUES ('".$BhRow['buy_his_id']."','".$hisRow['product_id']."','".$hisRow['qty_ses']."','".$hisRow['price_ses']."','".$hisRow['total_ses']."')");
			}
			
			//ลบรายการในเซสชั่นทิ้ง
			mysql_query("DELETE FROM buy_detail_session");
			
			header('Location: buy_history.php');
			
			echo "<script>alert('บันทึกรายการเรียบร้อยแล้วค่ะ');</script>";
		} else {
			$save = "กรุณากรอกวันที่และเลขที่บิลด้วยค่ะ";
		}
		
}

$objQuery = mysql_query("SELECT * FROM buy_detail_session,product,unit WHERE buy_detail_session.product_id = product.product_id AND unit.unit_id = product.unit_id ORDER BY buy_detail_ses_id");
?>
<div class="box">
  <div class="left"></div>
  <div class="right"></div>
    <div class="heading"><h1>เพิ่มประวัติการซื้อ เฮือนคำ รีสอร์ท</h1>
    <div class="buttons"><a onclick="CheckDate();" class="button"><span>บันทึก</span></a><a onclick="JavaScript:if(confirm('ยืนยันการยกเลิกรายการนี้?')==true){window.location='buy_history.php?Action=Cancle';}" class="button"><span>ยกเลิก</span></a></div></div>
  <div class="content">
  <form action="?action=add" name="formadd" method="post" id="formadd">
    <table class="form" id="form">
      <tr>
        <td>วันที่ : <input type="text" name="date" id="date" class="listform" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; เลขที่บิล : <input type="text" name="bill" id="bill" class="listform" /></td>
      </tr>
          </table>
       </form>
       
  <table class="list">
        <thead>
          <tr>
          	<td  width="5%" style="text-align: center;">ลบ</td>
            <td  width="5%" style="text-align: center;">ลำดับ</td>
            <td class="center">รายละเอียด</td>
            <td class="center" width="15%">จำนวน</td>
            <td class="center" width="15%">ราคาต่อหน่วย</td>
            <td class="center" width="15%">จำนวนเงิน</td>
          </tr>
        </thead>
        <tbody>
<?php
	$num=0;
	while($row = mysql_fetch_array($objQuery))
		{
			$num++;
?>
          <tr>
            <td style="text-align: center;"><img src="image/delete.png" width="16px" height="16px" border="0" style="cursor:pointer;" onclick="JavaScript:if(confirm('ยืนยันการลบรายการ?')==true){window.location='buy_history.php?Action=delete&id=<?php echo $row["buy_detail_ses_id"]; ?>';}" /></td>
            <td style="text-align: center;"><?php echo $num;?></td>
            <td class="left" style="padding-left:20px"><?php echo $row["product_name"];?></td>
            <td class="right" style="padding-right:20px"><?php echo number_format($row["qty_ses"], 2,'.',',')." ".$row['unit_name'];?></td>
            <td class="right" style="padding-right:20px"><?php echo number_format($row["price_ses"], 2,'.',',');?></td>
            <td class="right" style="padding-right:20px"><?php echo number_format($row["total_ses"], 2,'.',',');?></td>
          </tr>
<?php
		$strTotal=$strTotal+$row["total_ses"];
		}
		if($num!='0'){
?>
          <tr>
            <td colspan="5" class="center"><strong>รวมเงิน</strong></td>
            <td class="right" style="padding-right:20px"><strong><?php echo number_format($strTotal, 2,'.',',');?></strong></td>
          </tr>
<?php 
		}
		if($num=='0'){
?>
		<tr>
			<td colspan="6" class="center">ไม่มีรายการ</td>
		</tr>
<?php
		}
?>
        </tbody>
      </table>


      <h1 align="center">เพิ่มรายการสินค้า</h1>
      <form action="?action=addlist" name="formaddlist" method="post" id="formaddlist">
      <table class="listshow">
      <thead>
      	<tr>
      		<td class="center">รายการ</td>
      		<td class="center">จำนวน</td>
      		<td class="center">ราคาต่อหน่วย</td>
      		<td class="center">จำนวนเงิน</td>
      		<td class="center">จัดการ</td>
      	</tr>
      	</thead>
      	<tbody>
      	 <tr>
      		<td class="center"><input type="text" name="list" id="list" size="30" class="listform" /></td>
      		<td class="center"><input type="text" name="qty" id="qty" size="10" class="listform" onkeyup="totalcash();" onkeydown="if(event.keyCode==13){document.formaddlist.submit();}" /></td>
      		<td class="center"><input type="text" name="price" id="price" size="10" class="listform" onkeyup="totalcash();" onkeydown="if(event.keyCode==13){document.formaddlist.submit();}" /></td>
      		<td class="center"><input type="text" name="total" id="total" size="10" class="listform" onkeyup="pricecash();" onkeydown="if(event.keyCode==13){document.formaddlist.submit();}" /></td>
      		<td class="center"><div class="buttons"><a onclick="CheckList();" class="button"><span>เพิ่ม</span></a></div></td>
      	</tr>
      	</tbody>
      </table>
      </form>
	<?php echo "<br><font color=\"red\"><center>$save</center></font>"; ?>
  </div>
</div>
</div>
</body>
</html>
